package com.mikewoo.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

/**
 * Title: ServerSocketChannelDemo.java
 * Description: ServerSocketChannel服务端 
 * 
 * author     Phantom
 * date       2016年5月19日 下午1:25:31
 * @version    1.0.0
 */
public class ServerSocketChannelDemo {
	public static void startServer() throws Exception {
		ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
		serverSocketChannel.socket().bind(new InetSocketAddress(8999));
		serverSocketChannel.configureBlocking(false); // 设置为非阻塞
		
		while (true) {
			SocketChannel socketChannel = serverSocketChannel.accept();
			if (socketChannel != null) {
				ByteBuffer byteBuffer = ByteBuffer.allocate(48);
				int size = socketChannel.read(byteBuffer);
				while (size > 0) {
					byteBuffer.flip(); // 转变读写模式
					Charset charset = Charset.forName("UTF-8");
					System.out.println(charset.newDecoder().decode(byteBuffer).toString());
					size = socketChannel.read(byteBuffer);
				}
				byteBuffer.clear();
				
				ByteBuffer responseBuf = ByteBuffer.wrap("hello 开始netty学习之旅".getBytes("UTF-8"));
				socketChannel.write(responseBuf);
				responseBuf.clear();
				socketChannel.close();
			}
		}
	}
	
	public static void main(String[] args) throws Exception {
		startServer();
	}
}
